"use client";

import { useState, useRef, useEffect } from 'react';
import Image from 'next/image';
import { getLogoUrl, getImageUrl } from '@/lib/utils';
import axios from 'axios';
import { Resizable } from 're-resizable';
import Draggable from 'react-draggable';

interface Message {
  role: 'user' | 'assistant';
  content: string;
}

interface DashScopeAssistantProps {
  logoUrl?: string;
  appId?: string;
  positionCorner?: 'bottom-right' | 'bottom-left';
  theme?: {
    primaryColor?: string;
    textColor?: string;
  };
}

// Add mobile detection utilities
const isMobile = () => {
  if (typeof window !== 'undefined') {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
      navigator.userAgent
    );
  }
  return false;
};

export function DashScopeAssistant({
  logoUrl = getLogoUrl(),
  appId = process.env.NEXT_PUBLIC_DASHSCOPE_APP_ID || 'YOUR_APP_ID',
  positionCorner = 'bottom-right',
  theme = {
    primaryColor: '#6366f1',
    textColor: '#ffffff'
  }
}: DashScopeAssistantProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [messages, setMessages] = useState<Message[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [dragPosition, setDragPosition] = useState({ x: 0, y: 0 });
  const dragNodeRef = useRef<any>(null);

  // Handle mobile state
  const [isMobileDevice, setIsMobileDevice] = useState(false);
  
  // Check if the user is on a mobile device
  useEffect(() => {
    setIsMobileDevice(isMobile());
  }, []);

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 处理发送消息
  const handleSendMessage = async () => {
    if (!inputValue.trim()) return;
    
    // 添加用户消息
    const userMessage: Message = { role: 'user', content: inputValue };
    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    setIsLoading(true);

    try {
      // 调用百炼API
      const apiKey = process.env.NEXT_PUBLIC_DASHSCOPE_API_KEY;
      
      if (!apiKey) {
        throw new Error('API Key未配置');
      }

      const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
      
      const data = {
        input: {
          prompt: inputValue,
          session_id: sessionId
        },
        parameters: {
          has_thoughts: true
        },
        debug: {}
      };

      const response = await axios.post(url, data, {
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        }
      });

      if (response.status === 200) {
        // 存储会话ID以便后续对话使用
        if (response.data.output.session_id && !sessionId) {
          setSessionId(response.data.output.session_id);
        }

        // 添加助手回复消息
        const assistantMessage: Message = { 
          role: 'assistant', 
          content: response.data.output.text 
        };
        setMessages(prev => [...prev, assistantMessage]);
      } else {
        throw new Error(`调用失败: ${response.data.message}`);
      }
    } catch (error) {
      console.error('调用百炼API出错:', error);
      
      // 添加错误消息
      const errorMessage: Message = { 
        role: 'assistant', 
        content: '抱歉，我遇到了一些问题，请稍后再试。' 
      };
      setMessages(prev => [...prev, errorMessage]);
    } finally {
      setIsLoading(false);
    }
  };

  // 处理按键按下事件
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };
  
  // 处理拖动结束
  const handleDragStop = (e: any, data: any) => {
    setDragPosition({ x: data.x, y: data.y });
  };

  // 位置样式
  const positionClass = positionCorner === 'bottom-left' 
    ? 'left-4 bottom-4' 
    : 'right-4 bottom-4';

  return (
    <div className={`fixed ${positionClass} z-50`}>
      {isOpen ? (
        <Draggable
          handle=".drag-handle"
          nodeRef={dragNodeRef}
          position={dragPosition}
          onStop={handleDragStop}
          bounds="body"
          disabled={isMobileDevice} // Disable dragging on mobile devices
        >
          <div ref={dragNodeRef}>
            <Resizable
              defaultSize={{
                width: 360,
                height: 500,
              }}
              minWidth={300}
              minHeight={400}
              maxWidth={isMobileDevice ? "95vw" : "80vw"}
              maxHeight={isMobileDevice ? "70vh" : "80vh"}
              className="backdrop-blur-md bg-gray-950/30 text-white rounded-lg shadow-lg flex flex-col"
              enable={isMobileDevice ? {
                top: false,
                right: false,
                bottom: false,
                left: false,
                topRight: false,
                bottomRight: false,
                bottomLeft: false,
                topLeft: false
              } : {
                top: true,
                right: true,
                bottom: true,
                left: true,
                topRight: true,
                bottomRight: true,
                bottomLeft: true,
                topLeft: true
              }}
              handleStyles={{
                right: { width: '10px', cursor: 'e-resize' },
                left: { width: '10px', cursor: 'w-resize' },
                top: { height: '10px', cursor: 'n-resize' },
                bottom: { height: '10px', cursor: 's-resize' },
                topRight: { width: '10px', height: '10px', cursor: 'ne-resize' },
                bottomRight: { width: '10px', height: '10px', cursor: 'se-resize' },
                bottomLeft: { width: '10px', height: '10px', cursor: 'sw-resize' },
                topLeft: { width: '10px', height: '10px', cursor: 'nw-resize' }
              }}
              handleClasses={{
                right: 'hover:bg-blue-500/30',
                left: 'hover:bg-blue-500/30',
                top: 'hover:bg-blue-500/30',
                bottom: 'hover:bg-blue-500/30',
                topRight: 'hover:bg-blue-500/30',
                bottomRight: 'hover:bg-blue-500/30',
                bottomLeft: 'hover:bg-blue-500/30',
                topLeft: 'hover:bg-blue-500/30'
              }}
            >
              {/* 头部 - 只有非移动设备上为可拖动 */}
              <div className={`flex justify-between items-center rounded-lg px-4 py-3 border-indigo-800/40 ${isMobileDevice ? '' : 'drag-handle cursor-move'}`}>
                <div className="flex items-center ">
                  <div className="w-8 h-8 mr-2 relative ">
                    <Image 
                      src={getImageUrl(logoUrl)}
                      alt="超灵感助手" 
                      fill 
                      className="object-contain pointer-events-none"
                      priority
                      loading="eager"
                    />
                  </div>
                  <h3 className="font-medium text-blue-100 select-none">超灵感智能助手</h3>
                </div>
                <button 
                  onClick={() => setIsOpen(false)}
                  className={`text-blue-200 hover:text-white transition-colors duration-200 p-2 -mr-2 -mt-1 touch-manipulation relative z-50 ${isMobileDevice ? 'w-10 h-10 flex items-center justify-center' : ''}`}
                  style={{ touchAction: 'manipulation' }}
                  aria-label="关闭聊天窗口"
                >
                  <div className={`flex items-center justify-center rounded-full bg-red-500/80 hover:bg-red-600 ${isMobileDevice ? 'w-8 h-8' : 'w-6 h-6'}`}>
                    ✕
                  </div>
                </button>
              </div>
              
              {/* Disable drag handles on mobile */}
              {!isMobileDevice && (
                <div className="absolute left-0 top-0 w-full h-full pointer-events-none">
                  {/* 左侧边框作为拖动区域 */}
                  <div className="absolute left-0 top-0 w-4 h-full drag-handle cursor-move pointer-events-auto" />
                  
                  {/* 右侧边框作为拖动区域 */}
                  <div className="absolute right-0 top-0 w-4 h-full drag-handle cursor-move pointer-events-auto" />
                  
                  {/* 上侧边框作为拖动区域 */}
                  <div className="absolute left-0 top-0 w-full h-4 drag-handle cursor-move pointer-events-auto" />
                  
                  {/* 下侧边框作为拖动区域 */}
                  <div className="absolute left-0 bottom-0 w-full h-4 drag-handle cursor-move pointer-events-auto" />
                </div>
              )}
              
              {/* 聊天内容区域 */}
              <div className="flex-1 overflow-y-auto p-4 space-y-4">
                {messages.length === 0 ? (
                  <div className="text-center text-indigo-300 mt-8">
                    <p>你好！我是超灵感智能助手，请问有什么可以帮助你的？</p>
                  </div>
                ) : (
                  messages.map((message, index) => (
                    <div 
                      key={index} 
                      className={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
                    >
                      <div 
                        className={`max-w-[80%] rounded-lg px-4 py-2 ${
                          message.role === 'user' 
                            ? 'bg-gradient-to-r from-indigo-600 to-blue-500 text-white shadow-md' 
                            : 'bg-gradient-to-r from-gray-800/70 to-indigo-900/70 text-white shadow-md'
                        }`}
                      >
                        <p style={{ whiteSpace: 'pre-wrap' }}>{message.content}</p>
                      </div>
                    </div>
                  ))
                )}
                {isLoading && (
                  <div className="flex justify-start">
                    <div className="bg-gradient-to-r from-gray-800/70 to-indigo-900/70 text-white rounded-lg px-4 py-2 shadow-md">
                      <div className="flex space-x-1">
                        <div className="w-2 h-2 bg-blue-300 rounded-full animate-bounce"></div>
                        <div className="w-2 h-2 bg-blue-300 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
                        <div className="w-2 h-2 bg-blue-300 rounded-full animate-bounce" style={{ animationDelay: '0.4s' }}></div>
                      </div>
                    </div>
                  </div>
                )}
                <div ref={messagesEndRef} />
              </div>
              
              {/* 输入区域 */}
              <div className="rounded-lg border-t border-indigo-800/40 p-3 bg-gradient-to-r from-indigo-900/50 to-blue-900/50">
                <div className="relative">
                  <textarea
                    value={inputValue}
                    onChange={(e) => setInputValue(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder="输入消息..."
                    className="w-full bg-gray-800/60 text-white rounded-lg pl-3 pr-10 py-2 focus:outline-none focus:ring-1 focus:ring-blue-500 resize-none"
                    rows={2}
                  />
                  <button
                    onClick={handleSendMessage}
                    disabled={isLoading || !inputValue.trim()}
                    className={`absolute right-2 bottom-2 rounded-full p-1.5 ${
                      isLoading || !inputValue.trim() 
                        ? 'bg-gray-700/50 text-blue-400/50 cursor-not-allowed' 
                        : 'bg-gradient-to-r from-cyan-500 to-blue-500 text-white hover:from-cyan-600 hover:to-blue-600 shadow-lg transition-all duration-200 cursor-pointer'
                    }`}
                  >
                    <svg 
                      xmlns="http://www.w3.org/2000/svg" 
                      viewBox="0 0 24 24" 
                      fill="currentColor" 
                      className="w-5 h-5"
                    >
                      <path d="M3.478 2.404a.75.75 0 0 0-.926.941l2.432 7.905H13.5a.75.75 0 0 1 0 1.5H4.984l-2.432 7.905a.75.75 0 0 0 .926.94 60.519 60.519 0 0 0 18.445-8.986.75.75 0 0 0 0-1.218A60.517 60.517 0 0 0 3.478 2.404Z" />
                    </svg>
                  </button>
                </div>
              </div>
            </Resizable>
          </div>
        </Draggable>
      ) : (
        <button 
          onClick={() => setIsOpen(true)}
          className="bg-gradient-to-r from-white to-blue-500 w-14 h-14 rounded-full flex items-center justify-center shadow-lg transition-all duration-300 transform hover:scale-105"
        >
          <div className="w-8 h-8 relative">
            <Image 
              src={getImageUrl(logoUrl)}
              alt="超灵感助手" 
              fill 
              className="object-contain"
              priority
              loading="eager"
            />
          </div>
        </button>
      )}
    </div>
  );
} 